package model

import (
	"ginblog/utils/errmsg"
	"github.com/jinzhu/gorm"
)

type Article struct {
	Category Category
	gorm.Model
	Title   string `gorm:"type:varchar(100);not null" json:"title"`
	Cid     int    `gorm:"type:int;not null" json:"cid"`
	Desc    string `gorm:"type:varchar(200)" json:"desc"`
	Content string `gorm:"type:longtext" json:"content"`
	Img     string `gorm:"type:varchar(100)" json:"img"`
}

//验证分类是否存在
func CheckArticle(title string) int {
	var model Article
	db.Select("id").Where("name", title).First(&model)
	if model.ID > 0 {
		return errmsg.ErrorArticleNotExist
	}
	return errmsg.SUCCESS
}

//新增分类
func AddArticle(model *Article) int {
	err = db.Create(&model).Error
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//查询分类
func GetArticle(title string) (*Article, int) {
	var model Article
	err = db.Where("title = ?", title).First(&model).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, errmsg.ERROR
	}
	return &model, errmsg.SUCCESS
}

//查询分类列表
func GetArticles(page int, pageSize int) ([]Article, int) {
	var models []Article
	var total int

	err = db.Limit(pageSize).Offset((page - 1) * pageSize).Find(&models).Count(&total).Error
	if err != nil && err != gorm.ErrRecordNotFound {
		return nil, 0
	}
	return models, total
}

//编辑分类
func EditArticle(id int, data *Article) int {
	var model Article
	var maps = make(map[string]interface{})
	maps["title"] = data.Title
	err = db.Model(&model).Where("id = ?", id).Update(maps).Error

	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}

//删除分类
func DeleteArticle(id int) int {
	var model Article
	err = db.Where("id = ?", id).Delete(&model).Error //软删除
	//err = db.Where("id = ?", id).Unscoped().Delete(&model).Error //删除
	if err != nil {
		return errmsg.ERROR
	}
	return errmsg.SUCCESS
}
